﻿using Nop.Core;
using Nop.Core.Domain.Customers;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Media;
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace Nop.Web.Controllers
{
    public class PictureController : BasePublicController
    {
        private readonly IPictureService _pictureService;
        private readonly ICustomerService _customerService;
        private readonly IGenericAttributeService _genericAttributeService;

        public PictureController(IPictureService pictureService,
            ICustomerService customerService,
            IGenericAttributeService genericAttributeService)
        {
            this._pictureService = pictureService;
            this._customerService = customerService;
            this._genericAttributeService = genericAttributeService;
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public virtual ActionResult AsyncUpload()
        {
            Stream stream = null;
            var fileName = "";
            var contentType = "";
            if (String.IsNullOrEmpty(Request["imgfile"]))
            {
                // IE
                HttpPostedFileBase httpPostedFile = Request.Files[0];
                if (httpPostedFile == null)
                    throw new ArgumentException("No file uploaded");
                stream = httpPostedFile.InputStream;
                fileName = Path.GetFileName(httpPostedFile.FileName);
                contentType = httpPostedFile.ContentType;
            }
            else
            {
                //Webkit, Mozilla
                stream = Request.InputStream;
                fileName = Request["imgfile"];
            }

            var fileBinary = new byte[stream.Length];
            stream.Read(fileBinary, 0, fileBinary.Length);

            var fileExtension = Path.GetExtension(fileName);
            if (!String.IsNullOrEmpty(fileExtension))
                fileExtension = fileExtension.ToLowerInvariant();

            if (String.IsNullOrEmpty(contentType))
            {
                switch (fileExtension)
                {
                    case ".bmp":
                        contentType = MimeTypes.ImageBmp;
                        break;
                    case ".gif":
                        contentType = MimeTypes.ImageGif;
                        break;
                    case ".jpeg":
                    case ".jpg":
                    case ".jpe":
                    case ".jfif":
                    case ".pjpeg":
                    case ".pjp":
                        contentType = MimeTypes.ImageJpeg;
                        break;
                    case ".png":
                        contentType = MimeTypes.ImagePng;
                        break;
                    case ".tiff":
                    case ".tif":
                        contentType = MimeTypes.ImageTiff;
                        break;
                    default:
                        break;
                }
            }

            var picture = _pictureService.InsertPicture(fileBinary, contentType, null);

            return Json(new
            {
                success = true,
                pictureId = picture.Id,
                imageUrl = _pictureService.GetPictureUrl(picture, 100)
            },
                MimeTypes.TextPlain);
        }

        /// <summary>
        /// 上传头像
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        [HttpPost]
        public virtual ActionResult UploadAvatar(string guid)
        {
            try
            {
                var customer = _customerService.GetCustomerByToken(guid);
                if (null != customer)
                {
                    Stream stream = null;
                    var fileName = "";
                    var contentType = "";
                    if (String.IsNullOrEmpty(Request["avatarfile"]))
                    {
                        // IE
                        HttpPostedFileBase httpPostedFile = Request.Files[0];
                        if (httpPostedFile == null)
                            throw new ArgumentException("No file uploaded");
                        stream = httpPostedFile.InputStream;
                        fileName = Path.GetFileName(httpPostedFile.FileName);
                        contentType = httpPostedFile.ContentType;
                    }
                    else
                    {
                        //Webkit, Mozilla
                        stream = Request.InputStream;
                        fileName = Request["avatarfile"];
                    }

                    var fileBinary = new byte[stream.Length];
                    stream.Read(fileBinary, 0, fileBinary.Length);

                    var fileExtension = Path.GetExtension(fileName);
                    if (!String.IsNullOrEmpty(fileExtension))
                        fileExtension = fileExtension.ToLowerInvariant();

                    if (String.IsNullOrEmpty(contentType))
                    {
                        switch (fileExtension)
                        {
                            case ".bmp":
                                contentType = MimeTypes.ImageBmp;
                                break;
                            case ".gif":
                                contentType = MimeTypes.ImageGif;
                                break;
                            case ".jpeg":
                            case ".jpg":
                            case ".jpe":
                            case ".jfif":
                            case ".pjpeg":
                            case ".pjp":
                                contentType = MimeTypes.ImageJpeg;
                                break;
                            case ".png":
                                contentType = MimeTypes.ImagePng;
                                break;
                            case ".tiff":
                            case ".tif":
                                contentType = MimeTypes.ImageTiff;
                                break;
                            default:
                                break;
                        }
                    }

                    var picture = _pictureService.InsertPicture(fileBinary, contentType, null);

                    _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AvatarPictureId, picture.Id);
                }
            }
            catch (Exception ex)
            {
                return Json(new { result = false, msg = ex.Message });
            }
            return Json(new { result = false, msg = "失败" });
        }
    }
}